<?php
/**
 * PostCategory.php
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */

/**
 * base class
 */
require_once 'Madoqua/Db/Table/Abstract.php';

/** Blog_Category */
require_once 'Category.php';

/** Blog_Post */
require_once 'Post.php';

/**
 * Blog_PostCategory
 *
 * intersection for posts and categories
 *
 * @category   Madoqua
 * @package    Module
 * @subpackage Blog
 */
class Blog_PostCategory extends Madoqua_Db_Table_Abstract {
    
    /**
     * table name
     *
     * @var string
     */
    protected $_name = 'post_category';
    
        
    /**
     * reference map
     *
     * @var array
     */
    protected $_referenceMap    = array(
        'Blog_Post' => array(
            'columns'           => 'post_id',
            'refTableClass'     => 'Blog_Post',
            'refColumns'        => 'id'
        ),
        'Blog_Category' => array(
            'columns'           => 'category_id',
            'refTableClass'     => 'Blog_Category',
            'refColumns'        => 'id'
        )
    );
    
    /**
     * clean all, matching post
     *
     * @param string|Blog_Post_Row $post
     * @return int the number of rows deleted
     */
    public function cleanPost($post) {
        if ($post instanceof Blog_Post_Row) {
            $post = $post->id;
        }
        
        return $this->delete('post_id = ' . (int) $post);
    }
    
    /**
     * update a post with new categories
     * 
     * this *deletes* the old categories for this post
     *
     * @param string|Blog_Post_Row $post
     * @param array $categories
     */
    public function updatePost($post, $categories = array()) {
        if ($post instanceof Blog_Post_Row) {
            $post = $post->id;
        } 
        $this->cleanPost($post);

        if ($categories) {
            foreach($categories as $category) {
                $this->insert(array(
                    'post_id' => $post,
                    'category_id' => $category 
                ));
            }
	}
    }
}
